using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
using FrameWork;

namespace NPC
{
    public class CowBehaviour : MonoBehaviour,IAttack,INPCSpawn
    {
        [Header("牛的行为信息")]
        [SerializeField] private float cowMoveSpeed;                // 牛的移动速度
        [SerializeField] private float cowAddSatietyIndex;          // 牛增加饱食度幅度
        [SerializeField] private float cowAddHealth;                // 牛增加血量
        [SerializeField] private GameObject beefPrefab;             // 牛肉预制体
        
        [Header("牛的状态信息")]
        [SerializeField] private CowState currentState;             // 当前状态
        [SerializeField] private float satietyIndexValue = 100f;    // 饱食度
        [SerializeField] private float healthValue = 100f;          // 血量
        [SerializeField] private float timeToChangeState;           // 状态切换时间，该时间后切换状态
        [SerializeField] private bool isInHurtByPlayer = false;     // 是否受到玩家攻击
        
        /*************** 临时变量 ****************/
        private float beDamageByPlayer = 0f;                        // 玩家伤害临时变量存储
        private bool isCanSwitchTargetPosition = true;              // NPC是否可以更新新的目标位置
        private Vector3 targetPosition = Vector3.zero;              // NPC移动目标位置
        [SerializeField]private Vector3 leftDoundaryPos = Vector3.zero;             // NPC移动左边界
        [SerializeField]private Vector3 rightDoundaryPos = Vector3.zero;            // NPC移动右边界
        
        private bool isEating = false;                               // 是否正在吃饭
        private float stateStartTime = 0f;                           // NPC进入受伤状态时间
        
        /*************** 挂载组件 ****************/
        private Animator animator;                                  // 动画组件

        /// <summary>
        /// 每次激活时初始化信息参数
        /// </summary>
        private void OnEnable()
        {
            // 初始化参数
            satietyIndexValue = 100f;                    // 饥饿值
            healthValue = 100f;                          // 血量
            currentState = CowState.Idle;                // 设置为Idle
            timeToChangeState = Random.Range(3f, 7f);    // 初始状态持续时间
            isInHurtByPlayer = false;                    // 是否受到玩家攻击
             
            // 临时变量初始化
            beDamageByPlayer = 0f;
            isCanSwitchTargetPosition = true;
            targetPosition = Vector3.zero;
            isEating = false;
            stateStartTime = 0f;
            
            // 组件获取
            animator = GetComponent<Animator>();
        }

        private void Update()
        {
            if (currentState == CowState.Dead) return;

            UpdateSatietyIndexAndHealth();
            CheckStateTransitions();
            ExecuteCurrentState();
        }

        #region State Switch Function

        /// <summary>
        /// 更新饥饿值和健康
        /// </summary>
        private void UpdateSatietyIndexAndHealth()
        {
            // 不在进食时候，饥饿值不减少
            if (!isEating)
            {
                // 饥饿值随时间减少
                satietyIndexValue -= Time.deltaTime;
                if (satietyIndexValue < 0) satietyIndexValue = 0;
            }

            if (satietyIndexValue >= 100f)
            {
                currentState = CowState.Idle;
                isEating = false;
            }
            
            if (healthValue <= 0)
            {
                DieAndGenerateBeef();
            }

            // 饥饿值高时恢复血量
            if (satietyIndexValue >= 80)
            {
                healthValue += Time.deltaTime * cowAddHealth;
                if (healthValue > 100) healthValue = 100;
            }
        }

        /// <summary>
        /// 改变状态
        /// </summary>
        private void CheckStateTransitions()
        {
            // 检查是否需要进入受伤状态
            if ((satietyIndexValue < 10) || isInHurtByPlayer)
            {
                stateStartTime = Time.time;
                currentState = CowState.InHurt;
                healthValue -= beDamageByPlayer;
                isInHurtByPlayer = false; // 重置标记
            }
            // 检查是否需要吃草
            else if (satietyIndexValue < 60)
            {
                currentState = CowState.Eating;
            }
            // 检查是否需要切换常规状态
            else if (currentState == CowState.Idle || currentState == CowState.Walking)
            {
                timeToChangeState -= Time.deltaTime;
                if (timeToChangeState <= 0)
                {
                    SwitchIdleOrWalkingState();
                }
            }
        }

        /// <summary>
        /// 移动和空闲状态切换
        /// </summary>
        private void SwitchIdleOrWalkingState()
        {
            currentState = currentState == CowState.Idle ? CowState.Walking : CowState.Idle;
            timeToChangeState = Random.Range(3f, 7f);
        }

        /// <summary>
        /// 执行状态
        /// </summary>
        private void ExecuteCurrentState()
        {
            switch (currentState)
            {
                case CowState.Idle:
                    // Debug.Log("牛处于空闲状态");
                    animator.Play("CowIdle");
                    break;
                case CowState.Walking:
                    // Debug.Log("牛正在行走");
                    animator.Play("CowWalk");
                    MoveToTartGetPosition();
                    break;
                case CowState.Eating:
                    // Debug.Log("牛正在吃草");
                    animator.Play("CowEating");
                    isEating = false;
                    AddSatietyIndexValue();
                    break;
                case CowState.InHurt:
                    // Debug.Log("牛处于受伤状态");
                    animator.Play("CowHurt");
                    if (Time.time - stateStartTime > animator.GetCurrentAnimatorStateInfo(0).length)
                        currentState = CowState.Idle;
                    break;
                case CowState.Dead:
                    // Debug.Log("牛已死亡");
                    break;
            }
        }

        #endregion

        #region Behavior Function

        /// <summary>
        /// NPC移动
        /// </summary>
        private void MoveToTartGetPosition()
        {
            if (isCanSwitchTargetPosition)
            {
                targetPosition = new Vector3(Random.Range(leftDoundaryPos.x, rightDoundaryPos.x), Random.Range(leftDoundaryPos.y, rightDoundaryPos.y), transform.position.z);
                isCanSwitchTargetPosition = false;
            }
            // 向目标位置移动
            transform.position = Vector3.MoveTowards(transform.position, targetPosition, Time.deltaTime * cowMoveSpeed);

            float dir = -1;
            // 设置NPC朝向
            // 如果目标点在左侧
            if (targetPosition.x < transform.position.x)
                dir = 1;
            
            // 设置Scale
            transform.localScale = new Vector3(dir, 1, 1);
            
            // 如果到达目标位置，可以切换新的目标位置
            if(Vector3.Distance(transform.position, targetPosition) < 0.1f)
                isCanSwitchTargetPosition = true;
        }
        
        /// <summary>
        /// 获得饱食度
        /// 提高饥饿值
        /// </summary>
        private void AddSatietyIndexValue()
        {
            satietyIndexValue += Time.deltaTime * cowAddSatietyIndex;
        }

        /// <summary>
        /// NPC死亡
        /// </summary>
        private void DieAndGenerateBeef()
        {
            currentState = CowState.Dead;
            // Debug.Log("牛死亡并生成牛肉");
            // 牛死亡，随机生成奖品
            if (Random.Range(0, 100) < 60)
            {
                Instantiate(beefPrefab, transform.position, transform.rotation);
            }
        
            // 通知史莱姆管理器生成新的史莱姆
            EventSystem.Instance.EventTrigger(EventName.EVENT_SLIME_COW);
        
            // TODO:生成死亡粒子
        
            // 放回对象池
            ObjectPool.Instance.Replace("Cow", gameObject);
        }

        #endregion

        #region Interface Function

        /// <summary>
        /// 战斗系统接口
        /// 由玩家调用
        /// </summary>
        /// <param name="damage">传入伤害</param>
        public void Attack(float damage)
        {
            isInHurtByPlayer = true;
            beDamageByPlayer = damage;
        }

        /// <summary>
        /// 实现NPC生成接口
        /// 设定当前NPC边界
        /// </summary>
        /// <param name="leftPos">传入左边界</param>
        /// <param name="rightPos">传入右边界</param>
        public void Spawn(Vector3 leftPos, Vector3 rightPos)
        {
            leftDoundaryPos = leftPos;
            rightDoundaryPos = rightPos;
        }

        #endregion
    }
}